package org.jground.rx.ui.zk;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.rx.RXAccess;
import org.jground.rx.RXClass;
import org.jground.rx.RXDataState;
import org.jground.rx.RXSearchCriteria;
import org.jground.rx.RXSystem;
import org.jground.rx.ui.IUISearchPanel;
import org.jground.rx.ui.UIHelper;
import org.jground.zk.zulX.GridX;
import org.jground.zk.zulX.HboxX;
import org.jground.zk.zulX.PanelX;
import org.jground.zk.zulX.WindowX;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Vbox;

public class UISearchPanelExtended extends WindowX implements EventListener,  IUISearchPanel<Component> {
    //
    // CLASS LEVEL
    //
    private static Log logger = LogFactory.getLog(UISearchPanelExtended.class);
    //
    // OBJECT LEVEL
    //
    private UIFrame uiFrame;
    // 
    // Search Criteria Widgets
    //
    private Textbox queryTB;
    private List<Checkbox> rxClassIncludeCBs;
    private Checkbox includeDeletedCB;
    private List<Checkbox> topLevelCBs = new ArrayList<Checkbox>(4);
    private Checkbox restrictToBeApprovedCB;
    private Checkbox includeAllCB;
    //
    private PanelX searchCriteriaePanel;
    // 
    private int numberOfSelctionMoids;
    //private RXSearchCriteria currentSC;

    public UISearchPanelExtended(UIFrame uiFrame) {
        logger.debug("start init");
        this.uiFrame = uiFrame;
        // this.setTitle("Search");
        // this.setBorder("normal");
        // this.setClosable(true);
        this.setTitle("");
        this.setBorder("none");
        this.setClosable(false);
        //
        // CREATE
        //
        searchCriteriaePanel = new PanelX("Search", "normal", true);
        searchCriteriaePanel.setBorder("normal");
        //
        rxClassIncludeCBs = new ArrayList<Checkbox>();
        ArrayList<String> moids = new ArrayList<String>();
        for (RXClass moc : RXSystem.getInstance().getRxService().getAllRXClasses()) {
            moids.add(moc.getMoid());
        }

        Vbox moidSelection = new Vbox();
        numberOfSelctionMoids = createMoidSelection(moidSelection, UIHelper.filterReadableTopLevelMoids(moids),
                rxClassIncludeCBs, "S");
        //
        queryTB = new Textbox();
        queryTB.setWidth("200px");
        //
        //
        includeDeletedCB = new Checkbox();
        restrictToBeApprovedCB = new Checkbox();
        includeAllCB = new Checkbox();
        //
        // resultLabel = new Label();
        // resultLabel.setStyle("padding: 4px;margin: 4px");
        //
        //
        // LAYOUT
        //

        // GRID for search criteria

        GridX grid = new GridX("*", "*");
        //

        // SEARCH TEXT
        grid.addAsRow(new Label("Search Text"), queryTB);
        //
        if (numberOfSelctionMoids > 1) {
            // INCLUDE ALL
            grid.addAsRow(new Label("Include All"), includeAllCB);
            // SELECTION
            grid.addAsRow(new Label(" "), moidSelection);
        } else {
            logger.info("number of MOID to select is less then 2. So we don't show any selection for search!");
        }
        // INCLUDE DELETED
        if (RXAccess.getInstance().isSysadmin()) {
            grid.addAsRow(new Label("Include Deleted"), includeDeletedCB);
        }
        // TO BE APPROVED
        grid.addAsRow(new Label("To Be Approved"), restrictToBeApprovedCB);
        HboxX gridHbox = new HboxX(grid);
        gridHbox.setStyle("padding: 4px");
        searchCriteriaePanel.add(gridHbox);
        // BUTTONS
        Hbox buttonBX = null;
        searchCriteriaePanel.add(buttonBX = new Hbox());
        // hbox.setStyle("padding: 4px");
        buttonBX.setSclass(UIStyles.BUTTONGROUP);
        //
        set(searchCriteriaePanel);
        //
        // this.add(resultPanel);
        // resultPanel.add(resultLabel);

        //
        // EVENTS
        //
        includeAllCB.addEventListener(Events.ON_CHECK, this);
    }

    private int createMoidSelection(Vbox vbox, List<String> moids, List<Checkbox> cbList, String style) {
        int counter = 0;
        for (String moid : moids) {
            RXClass moc = RXSystem.getInstance().getRxService().getRXClass(moid);
            if (moc == null) {
                continue;
            }
            if (RXAccess.getInstance().canRead(moc)) {
                Checkbox cb = new Checkbox();
                String name = moc.getName();
                cb.setLabel(name);
                cb.setParent(vbox);
                cbList.add(cb);
                cb.setAttribute("moid", moid);
                topLevelCBs.add(cb);
                counter++;
            }
        }
        return counter;
    }

    public void reset() {
        queryTB.setValue("");
        includeAllCB.setChecked(false);
        includeDeletedCB.setChecked(false);
        restrictToBeApprovedCB.setChecked(false);
        for (Checkbox cb : topLevelCBs) {
            cb.setChecked(false);
            cb.setDisabled(false);
        }

    }

    public void onEvent(Event e) throws Exception {

        if (e.getTarget() == includeAllCB) {
            for (Checkbox cv : topLevelCBs) {
                cv.setDisabled(includeAllCB.isChecked());
            }
        }
    }

    public void setSearchCriteria(RXSearchCriteria sc) {

    }

    public RXSearchCriteria getSearchCriteria() {
        RXSearchCriteria sc = new RXSearchCriteria();
        //
        String searchString = this.queryTB.getValue();
        sc.setSearchString(searchString);
        logger.debug("query: " + queryTB.getValue());
        // MODataStates defaults
        sc.addIncludedDataStates(RXDataState.APPROVED, RXDataState.STORED);
        //
        if (includeDeletedCB.isChecked()) {
            sc.addIncludedDataStates(RXDataState.DELETED, RXDataState.DELETED_UNAPPROVED);
        }
        if (restrictToBeApprovedCB.isChecked()) {
            sc.setIncludedDataStates(RXDataState.DELETED_UNAPPROVED, RXDataState.STORED);
            includeDeletedCB.setChecked(false);
        }
        for (Checkbox cb : topLevelCBs) {
            String moid = (String) cb.getAttribute("moid");
            if (cb.isChecked() || includeAllCB.isChecked()) {
                sc.addIncludedMoids(moid);
            }
        }
        return sc;
    }

    public void beforeClose() {}

    public void beforeShow() {}

    public Component getView() {
        return this;
    }

    public UIFrame getUiFrame() {
        return uiFrame;
    }

}